#include "videodetect.h"
#include "ui_videodetect.h"
#include <QLabel>
#include <QImage>
#include <QPixmap>
#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

CascadeClassifier cascade;



videoDetect::videoDetect(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::videoDetect)
{
    ui->setupUi(this);
}


//QImage *test = new QImage("C:/Users/vivi134/Desktop/Photos/test.jpg");
//ui->origin->setPixmap(QPixmap::fromImage(*test));


videoDetect::~videoDetect()
{
    delete ui;
}

void videoDetect::on_show_clicked()
{
    VideoCapture video;
    video.open(0);

    if (!video.isOpened()) {
    cout << "摄像头加载出错！" << endl;
    exit(-1);
    }

    //！！！重要！！！这是一个opencv自带已训练的人脸识别算法，具体路径需要根据opencv库安装位置更改！！！
    const string casPath = "D:/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml";

    //检测是否成功加载级联分类器
    if (!cascade.load(casPath)) {
        cout << "算法加载失败！" << endl;
        exit(-1);
    }

    ui->origin->setScaledContents(true);

    while (1) {
        Mat vClip;
        video >> vClip;  //视频转为图像

        if (vClip.empty()) {
            break;      //取完最后一帧后结束（使用摄像头的话必须手动结束）
        }

        Mat imgGray;
        cvtColor(vClip, imgGray, COLOR_BGR2GRAY);

        vector<Rect> faces(0);
        cascade.detectMultiScale(imgGray, faces, 1.1, 2, 0, Size(30, 30));  //调用人脸识别算法

        QString sNum = QString::number(faces.size());
        ui->numShow->setText(sNum); //实时输出人脸数

        if (faces.size() > 0) {
            for (size_t i = 0; i < faces.size(); i++) {
                rectangle(vClip, faces[i], Scalar(0, 0, 255), 2, 8, 0);  //生成矩形框出人脸

            }
        }
        else {
            cout << "No faces!" << endl;
        }

        //输出有框的人脸图

        Mat temp;
        cvtColor(vClip,temp,COLOR_BGR2RGB);//BGR convert to RGB
        QImage Qtemp = QImage((const unsigned char*)(temp.data),
                                temp.cols, temp.rows, temp.step,
                                QImage::Format_RGB888);

        ui->origin->setPixmap(QPixmap::fromImage(Qtemp));

        uchar c = waitKey(1); //waitkey 1ms的延迟
        QApplication::processEvents();
    }


}

void videoDetect::on_exit_clicked()
{
    exit(0);
}
